import axios from "axios";
let tokenObj: any = void 0;

const getToken = () => {
  return new Promise((resolve, reject) => {
    axios({
      url: "https://www.yuxin-ai.com/fastapi/api/user/login",
      method: "post",
      headers: {
        Connection: "keep-alive",
        "Content-Type": "application/json",
      },
      // responseType: "stream",
      data: {
        account: "hj9801",
        password: "52a584414a11cabc5a1b1bd24c06e049",
      },
    })
      .then((response) => {
        const { token, user_id } = response.data.data;
        const obj = {
          token,
          user_id,
        };
        tokenObj = obj;
        resolve(obj);
      })
      .catch((err) => {
        reject();
        //  console.log(err);
      });
  });
};

export const gptChat = async (msg: string, callback: Function) => {
  return new Promise(async (resolve, reject) => {
    console.log(tokenObj);
    if (!tokenObj) {
      const tk = await getToken().catch(() => {});
      console.log(tokenObj);
      console.log("到这里失败");

      if (!tk) return reject();
    }

    console.log("到了这里");

    await axios({
      url: "https://www.yuxin-ai.com/fastapi/api/chat",
      method: "post",
      headers: {
        Connection: "keep-alive",
        "Cache-Control": "no-cache",
      },
      responseType: "stream",
      data: {
        ...tokenObj,
        msg: [
          {
            content: msg,
            role: "user",
          },
        ],
        model: "gpt-3.5-turbo",
      },
    }).then((response) => {
      response.data.on("data", (chunk: any) => {
        const str = Buffer.from(chunk).toString("utf-8");
        var regex = /\{(.*)\}/g;
        var match = regex.exec(str);
        try {
          if (match[0]) {
            const obj = JSON.parse(match[0]);
            console.log(obj);
            // res.write(JSON.stringify(obj.choices[0].delta));
            callback({
              data: obj.choices[0].delta.content,
              status: 1,
            });
          }
        } catch {}
      });
      response.data.on("end", (data: any) => {
        // 数据接收完成的逻辑

        resolve({
          status: 2,
        });
      });
    });
  });
};
